import core.buffer.Buffer;
import core.net.protocol.IProtocol;
import game.Player;
import game.Scene;
import core.net.NetConfig;
import core.net.TCPClient;
import core.net.protocol.FrameCheckP;
import core.net.protocol.MoveP;
import core.net.protocol.Protocol;

import java.util.concurrent.atomic.AtomicInteger;

public class ClientApp {

    public static Scene scene;
    private static AtomicInteger _frame = new AtomicInteger(0);

    public static void main(String[] args) throws InterruptedException {

        Protocol.instance().register(FrameCheckP.TYPE, FrameCheckP.class);
        Protocol.instance().register(MoveP.TYPE, MoveP.class);
//        FrameCheckP p = Protocol.instance().get(FrameCheckP.TYPE);
//        p.frame = 1;
//        Buffer buffer = Protocol.instance().serialize(p);
//        buffer.read();
//        System.out.println(Protocol.instance().deserialize(buffer));
        NetConfig config = new NetConfig(5000, 32, 10 * 1000);
        TCPClient client = new TCPClient("127.0.0.1", 32145, config);
        Player player = new Player();
        scene = new Scene();
        scene._handleCMD = ClientApp::handleCMD;
        client.connectedHandler(connection -> {
            player.connection(connection);
            scene.entry(player);
        });
        client.open();
        MoveP p = Protocol.instance().get(MoveP.TYPE);
        p.x = 1;
        p.y = 2;
        while (true) {
            scene.update();
//            System.out.println("[update] frame " + _frame.get());
            p.frame = _frame.get();
            player.send(p);
            _frame.incrementAndGet();
        }
    }

    public static void handleCMD(IProtocol cmd, Player player) {
        System.out.println("[receive] " +cmd);
        switch (cmd.protocolType()) {
            case FrameCheckP.TYPE:
                FrameCheckP f = (FrameCheckP) cmd;
                _frame.set(f.frame+1);
                break;
            case MoveP.TYPE:
                System.out.println("[Move] "+cmd);
                break;
        }
    }
}
